package com.sq.partner.manager.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.sq.partner.manager.common.ActirationErrorInfo;
import com.sq.partner.manager.common.Constants;
import com.sq.partner.manager.common.Result;
import com.sq.partner.manager.mybatis.model.ActirationCardUserDto;
import com.sq.partner.manager.mybatis.model.DeptDto;
import com.sq.partner.manager.mybatis.model.GatewayRole;
import com.sq.partner.manager.mybatis.model.GatewayUser;
import com.sq.partner.manager.mybatis.model.GatewayUserRole;
import com.sq.partner.manager.service.ActirationCardCirculationService;
import com.sq.partner.manager.service.ActirationCardPowerService;
import com.sq.partner.manager.service.IGatewayUserService;
import com.sq.partner.manager.sso.UMClient;
import com.sq.partner.manager.sso.webservice.UserInfo;
import com.sq.partner.manager.util.MD5Util;
import com.sq.partner.manager.util.Page;
import com.sq.partner.manager.util.PasswordUtil;
import com.sq.partner.manager.util.SqlUtil;
import com.sq.partner.manager.util.StrUtil;
/**
 * 激活卡用户权限管理
 * @author LHX
 *
 */
@Controller
@RequestMapping(value = "/cardPower")
public class ActirationCardPowerController {
	@Resource
	private ActirationCardCirculationService circulationService; 
	@Resource
	private IGatewayUserService userService;
	@Resource
	private ActirationCardPowerService powerService;
	/**
	 * 返回激活卡人员管理页面
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/list")
	public String getIndex() throws Exception {
		return "actirationCard/power/index";
	}
	/**
	 * 返回激活卡人员新增
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/checkOrAdd")
	public String getAdd() throws Exception {
		return "actirationCard/power/add";
	}
	/**
	 * 查询当前机构的下级机构
	 * @param session
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/querycompanydown", method = RequestMethod.POST)
	@ResponseBody
	public List<DeptDto> querycomdown(HttpSession session, String id) throws Exception{
		if (id == null) {
			GatewayUser gatewayuser=(GatewayUser) session.getAttribute(Constants.SESSION_USER);
			id = gatewayuser.getUserComcode();
			// 查询本级机构
			return circulationService.queryComAndDown(id);
		}
		return circulationService.queryComDown(id);
	}
	/**
	 * 获取当前登录人员的激活卡权限信息
	 * @param session
	 * @return
	 * @throws Exception
	 */
	 @RequestMapping(value = "/queryPower", method = RequestMethod.POST)
	 @ResponseBody
	 public String queryPower(HttpSession session) throws Exception {
		//获取当前登录机构
		 GatewayUser gatewayuser=(GatewayUser) session.getAttribute(Constants.SESSION_USER);
		 return gatewayuser.getUserPower();
	 }
	 /**
	  * 增加用户（激活卡）
	  * @param session
	  * @param username 用户姓名
	  * @param email email
	  * @param usercode 用户代码
	  * @param telephone 电话
	  * @param comCode 机构代码
	  * @param roleName 角色名称
	  * @param powerCode 权限代码
	  * @return
	  * @throws Exception
	  */
	 @RequestMapping(value = "/adduser", method = RequestMethod.POST)
	 @ResponseBody
	 public Result addUser(HttpSession session,String username,String email,String usercode,String telephone,String comCode,@RequestParam List<String> roleName,String powerCode) throws Exception {
	     //校验总公司角色仅能总公司人员设置
	     if(checkHeadquarters(roleName, comCode)){
	         GatewayUser u = (GatewayUser)session.getAttribute(Constants.SESSION_USER);
//	         Map<String,String> userMap = new HashMap<String, String>();
//	         userMap.put("userCode", usercode);
//	         userMap.put("isCard", "1");
//	         GatewayUser jhkUser = (GatewayUser)userService.queryUserCount(userMap);
//	         //	         如果存在该激活卡用户，提示编辑该用户的激活卡角色、机构和权限
//	         if (null!=jhkUser) {
//	             return Result.error(ActirationErrorInfo.USER_12);
//	         }
	         Map<String,String> map = new HashMap<String, String>();
             map.put("userCode", usercode);
             GatewayUser ur = (GatewayUser)userService.queryUserCount(map);
             //如果存在该激活卡用户，提示编辑该用户的激活卡角色、机构和权限
             if (ur != null && StrUtil.isNotEmpty(ur.getUserComcode())) {
                 return Result.error(ActirationErrorInfo.USER_12);
             }
	         //		 如果存在该用户，新增该用户的激活卡角色、机构和权限
	         if(null!=ur){
	             ur.setUserComcode(comCode);
	             ur.setUserPower(powerCode);
	             boolean updateflag=true;
	             String message="";
	             //保存
	             if(powerService.updateUserComPower(ur)){
	                 //删除掉该用户关联的激活卡相关角色
	                 HashMap<String,Object> delmap=new HashMap<String, Object>();
	                 //添加激活卡角色条件
	                 delmap.put("flag", Constants.ACTIR_CARD_ROLE+"%");
	                 delmap.put("userid", ur.getUserid());
	                 powerService.delUserRole(delmap);
	                 updateflag=putRole(roleName, ur.getUserid(), u.getUserid());

	             }else{
	                 updateflag=false;
	                 message=ActirationErrorInfo.USER_3;
	             }
	             //判断是否都执行成功
	             if(updateflag){
	                 return Result.success(ActirationErrorInfo.USER_4);
	             }else{
	                 return Result.error(message);
	             }
	         }
	         //新增角色
	         else{
	             UserInfo userInfo = UMClient.getUser(usercode);
	             if(userInfo==null){
	                 return Result.error("notexist");
	             }else{
//	                 if (!userInfo.getOrgCode().contains("comCode")) {
//	                     return Result.error("用户" + usercode + "不在此机构下");
//	                 }
	                 GatewayUser user=new GatewayUser();
	                 String password = PasswordUtil.getPassword();
	                 user.setUserPwd(MD5Util.md5(password));
	                 user.setUserCode(usercode);
	                 user.setUserName(username);
	                 user.setEmail(email);
	                 user.setTelephone(telephone);
	                 user.setStatus(new Integer(1));
	                 user.setOperUser(u.getUserid());
	                 user.setOperTime(new Date());
	                 //添加归属机构 
	                 user.setUserComcode(comCode);
	                 //添加权限
	                 user.setUserPower(powerCode);
	                 //添加员工号
	                 user.setEmployeeNo(userInfo.getEmployeeNo());
	                 if(userService.addUser(user)){
	                     //查询刚才添加的用户
	                     user=userService.queryUserCount(map);
	                     //先删除该用户下所有角色
	                     //					 userService.removeAllRolesFromUser(user.getUserid());
	                     //用户添加成功，开始添加角色信息
	                     boolean roleflag=putRole(roleName, user.getUserid(), u.getUserid());
	                     if(roleflag){
	                         return Result.success("添加成功,初始密码是:<a style=\"color:red\">"+password+"</a>请牢记!");
	                     }else{
	                         return Result.success("添加成功,初始密码是:<a style=\"color:red\">"+password+"</a>请牢记!设置角色失败，请重新设置");
	                     }

	                 }else{
	                     return Result.error(ActirationErrorInfo.USER_3);
	                 }
	             }
	         }
	     }else{
	         return Result.error(ActirationErrorInfo.USER_11);
	     } 
	 }
	 /**
	  * 插入用户角色信息关联表数据
	  * @param roleList 角色list
	  * @param userid 用户id
	  * @param operid 操作用户id
	  * @return
	  * @throws Exception
	  */
	 private boolean putRole(List<String> roleName,long userid,long operid) throws Exception{
		 boolean flag=true;
		 //查询角色
		 List<GatewayRole> roleList=powerService.queryUserRole(roleName);
		 for(GatewayRole role:roleList){
			 GatewayUserRole urr = new GatewayUserRole();
			 urr.setUserid(userid);
			 urr.setRoleid(role.getRoleid());
			 urr.setOperUser(operid);
			 urr.setOperTime(new Date());
			 //添加角色
			 flag = userService.setRoleToUser(urr);
			 if(!flag){
				 break;
			 }
		 }
		 return flag;
	 }
	 private boolean checkHeadquarters(List<String> roleName,String userComcode) throws Exception{
	     boolean flag=true;
	     //查询角色
         List<GatewayRole> roleList=powerService.queryUserRole(roleName);
	     for(GatewayRole role:roleList){
	         if(Constants.ACTIR_CARD_ROLE_ZGS.equals(role.getRoleName())&&!"00".equals(userComcode)){
	             flag=false;
	         }
	     }
	     return flag;
	 }
	 /**
	  * 删除用户
	  * @param session
	  * @param userid
	  * @return
	  * @throws Exception
	  */
	 @RequestMapping(value = "/deluser", method = RequestMethod.POST)
	 @ResponseBody
	 public Result removeUser(HttpSession session,String userid) throws Exception {
		 GatewayUser operuser = (GatewayUser)session.getAttribute(Constants.SESSION_USER);
		//查询需要操作的人员信息
		 Map<String,String> map = new HashMap<String, String>();
		 map.put("userid", userid);
		 GatewayUser ur = (GatewayUser)userService.queryUserCount(map);
		 if(powerService.removeUser(ur, operuser)){
			 return Result.success(ActirationErrorInfo.USER_5);
		 }else{
			 return Result.error(ActirationErrorInfo.USER_6);
		 }
		 
	 }
	 /**
	  * 修改用户信息
	  * @param session
	  * @param userid 用户id
	  * @param telphone 电话
	  * @param email
	  * @param comCode 归属机构
	  * @param power 权限
	  * @param roleName 角色名称
	  * @return
	  * @throws Exception
	  */
	 @RequestMapping(value = "/updateuser", method = RequestMethod.POST)
	 @ResponseBody
	 public Result udpateUser(HttpSession session,String userid,String username,String telphone,String email,String comCode,String power,@RequestParam List<String> roleName) throws Exception {
	     GatewayUser operuser = (GatewayUser)session.getAttribute(Constants.SESSION_USER);
	     if(StrUtil.isNotEmpty(userid)){
	         Map<String,String> map = new HashMap<String, String>();
	         map.put("userid", userid);
	         //查询是否存在用户
	         GatewayUser user = (GatewayUser)userService.queryUserCount(map);
	         if(null!=user){
	             //更新信息判断
	             if(StrUtil.isNotEmpty(telphone)){
	                 user.setTelephone(telphone);
	             }
	             if(StrUtil.isNotEmpty(email)){
	                 user.setEmail(email);
	             }
	             if(StrUtil.isNotEmpty(comCode)){
	                 user.setUserComcode(comCode);
	             }
	             if(StrUtil.isNotEmpty(power)){
	                 user.setUserPower(power);
	             }
	             if(StrUtil.isNotEmpty(username)){
	                 user.setUserName(username);;
	             }
	             //保存用户信息
	             if(userService.saveUser(user)){
	                 if(null!=roleName){
	                     //校验总公司角色仅能总公司人员设置
	                     if(checkHeadquarters(roleName, comCode)){
	                         HashMap<String,Object> rolemap=new HashMap<String, Object>();
	                         rolemap.put("flag", Constants.ACTIR_CARD_ROLE+"%");
	                         rolemap.put("userid", user.getUserid());
	                         //删除所有角色信息
	                         powerService.delUserRole(rolemap);
	                         //	添加新的角色关联信息
	                         if(putRole(roleName, user.getUserid(), operuser.getUserid())){
	                             return Result.success(ActirationErrorInfo.USER_7);
	                         }else{
	                             return Result.error(ActirationErrorInfo.USER_8);
	                         }
	                     }else{
	                         return Result.error(ActirationErrorInfo.USER_11);
	                     }
	                 }else{
	                     return Result.success(ActirationErrorInfo.USER_7);
	                 }
	             }else{
	                 return Result.error(ActirationErrorInfo.USER_3);
	             }
	         }
	         else{
	             return Result.error(ActirationErrorInfo.USER_9);
	         }
	     }else{
	         return Result.error(ActirationErrorInfo.DEFINE_CARD_13);
	     }
	 }
	 /**
	  * 分页查询用户
	  * @param page
	  * @param userCode
	  * @param userName
	  * @param comCode
	  * @param comName
	  * @param roleId
	  * @param power
	  * @return
	  * @throws Exception
	  */
	 @RequestMapping(value = "/queryuser", method = RequestMethod.POST)
	 @ResponseBody
	 public Page<GatewayUser> queryUser(HttpSession session, Page<GatewayUser> page,String userCode,String userName,String comCode,String comName,String roleId,String power) throws Exception {
	    GatewayUser operuser = (GatewayUser)session.getAttribute(Constants.SESSION_USER);
	    //初始化分页信息
		Map<String,Object> paramMap = SqlUtil.buildPageMap(page);
		//查询条件
		if(StrUtil.isNotEmpty(userCode)){
			paramMap.put("usercode", userCode);
		}
		if(StrUtil.isNotEmpty(userName)){
			paramMap.put("username", userName);
		}
		if(StrUtil.isNotEmpty(comCode)){
			paramMap.put("comcode", comCode);
		}
		// 只能查询本级及下级机构的人员 lfd added 20181008 start
		if(StrUtil.isNotEmpty(operuser.getUserComcode()) && !Constants.DICT_PROVINCE_CODE.equals(operuser.getUserComcode())){ 
		    paramMap.put("userComcode", operuser.getUserComcode());
		}
		// 只能查询本级及下级机构的人员 lfd added 20181008 end
		if(StrUtil.isNotEmpty(comName)){
			paramMap.put("comname", "%"+comName+"%");
		}
		page.setMap(paramMap);
		page=powerService.queryUser(page);
		//操作查询
		return page;
	 }
	 /**
	  * 返回所有激活卡角色
	  * @return
	  * @throws Exception
	  */
	 @RequestMapping(value = "/queryallrole", method = RequestMethod.POST)
	 @ResponseBody
	 public List<GatewayRole> queryAllRole() throws Exception {
		 return powerService.queryAllRole(Constants.ACTIR_CARD_ROLE+"%");
	 }
	 /**
	  * 根据用户获取角色信息
	  * @param userid
	  * @return
	  * @throws Exception
	  */
	 @RequestMapping(value = "/getuserrole", method = RequestMethod.POST)
	 @ResponseBody
	 public List<GatewayRole> queryUserRole(String userid) throws Exception {
		 return powerService.queryUserRoles(userid);
	 }
	 /**
	  * 查询用户信息
	  * @param userid
	  * @return
	  * @throws Exception
	  */
	 @RequestMapping(value = "/getuserinfo", method = RequestMethod.POST)
	 @ResponseBody
	 public ActirationCardUserDto queryUserInfo(String userid) throws Exception {
		 ActirationCardUserDto userDto=new ActirationCardUserDto();
		 Map<String,String> map = new HashMap<String, String>();
		 map.put("userid", userid);
		 GatewayUser user = (GatewayUser)userService.queryUserCount(map);
		 user.setUserPwd("");
		 if(null!=user){
			 List<GatewayRole> roleList=powerService.queryUserRoles(userid);
			 userDto.setGatewayUser(user);
			 userDto.setGatewayRoleList(roleList);
		 }
		 return userDto;
	 }
	 /**
	  * 校验当前登录用户是否有总公司管理员权限
	  * @param session
	  * @return
	  * @throws Exception
	  */
	 @RequestMapping(value = "/getusercompower", method = RequestMethod.POST)
	 @ResponseBody
	 public Result queryUserComPower(HttpSession session) throws Exception {
		 GatewayUser gatewayuser=(GatewayUser) session.getAttribute(Constants.SESSION_USER);
		 List<GatewayRole> roleList=powerService.queryUserRoles(gatewayuser.getUserid()+"");
		 StringBuffer roleStr=new StringBuffer("");
		 //拼接角色串
		 for(GatewayRole role:roleList){
			 roleStr.append(role.getRoleName()+",");
		 }
		 //判断角色串是否包含管理员及总公司（按照名称）
		 if(roleStr.toString().contains(Constants.ACTIR_CARD_ROLE_GLY)&&roleStr.toString().contains(Constants.ACTIR_CARD_ROLE_ZGS)){
			 return Result.success("成功查询",true);
		 }else{
			 return Result.success("成功查询",false);
		 }
		 
	 }
	 
	 
}
